//
// Created by xdc on 2025/11/8.
//
#include "borrow.h"
void borrow_book() {
    const char *check_status_sql = "select user_status from front_user where id=?";
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, check_status_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "借阅失败：查询用户状态出错 - %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, login_user_id);
    int user_status;
    if (sqlite3_step(stmt) == SQLITE_ROW) {
        user_status = sqlite3_column_int(stmt, 0);
    } else {
        fprintf(stderr, "借阅失败：未找到当前用户信息\n");
        sqlite3_finalize(stmt);
        return;
    }
    sqlite3_finalize(stmt);

    if (user_status == 1) {
        printf( "借阅失败：您的账号已被拉黑，无法借阅图书\n");
        return;
    }

    char book_name[50];
    printf("\n===== 图书借阅 =====");
    printf("\n当前登录用户ID：%d\n", login_user_id);
    printf("请输入要借阅的图书名字：");
    scanf("%s",book_name);


    const char *check_book_sql = "select book_name,stock from book where book_name=?";
    rc = sqlite3_prepare_v2(db, check_book_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "查询图书SQL预编译失败：%s\n", sqlite3_errmsg(db));
        return;
    }
    sqlite3_bind_text(stmt, 1, book_name, -1, SQLITE_TRANSIENT);

    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW) {
        printf("未找到名字为《%s》的图书,请重新输入！\n",book_name);
        sqlite3_finalize(stmt);
        return;
    }

    int stock = sqlite3_column_int(stmt, 1);
    sqlite3_finalize(stmt);


    if (stock <= 0) {
        printf( "借阅失败：《%s》当前库存不足\n", book_name);
        return;
    }

    const char *insert_record_sql =
            "insert into borrow_record (user_id, book_name, borrow_time, due_time, status) "
            "values (?, ?, CURRENT_TIMESTAMP, datetime('now', '+30 days'), 0);";
    rc =sqlite3_prepare_v2(db, insert_record_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "插入记录预编译失败：%s\n", sqlite3_errmsg(db));
        return;
    }
    sqlite3_bind_int(stmt, 1, login_user_id);
    sqlite3_bind_text(stmt, 2, book_name, -1, SQLITE_TRANSIENT);
    if (sqlite3_step(stmt) != SQLITE_DONE) {
        fprintf(stderr, "借阅失败：记录插入出错 - %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return;
    }
    sqlite3_finalize(stmt);

    const char *update_stock_sql = "update book set stock = stock - 1 where book_name=?";
    rc = sqlite3_prepare_v2(db, update_stock_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "库存更新预编译失败：%s\n", sqlite3_errmsg(db));
        return;
    }
    sqlite3_bind_text(stmt, 1, book_name, -1, SQLITE_TRANSIENT);
    if (sqlite3_step(stmt) != SQLITE_DONE) {
        fprintf(stderr, "借阅失败：库存更新出错 - %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return;
    }
    sqlite3_finalize(stmt);

    printf("借阅成功！《%s》\n", book_name);
    printf("当前库存：%d本\n", stock - 1);
    printf("应还日期：30天内\n");
}